// 启动项目并运行后台程序
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const port = 12317;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const exec = require('child_process').exec;
const fork = require('child_process').fork;
const colorsjs = require('colors')

//打开默认浏览器
const openDefaultBrowser = (url) => {
  switch (process.platform) {
    case "darwin":
      exec('open ' + url);
      break;
    case "win32":
      exec('start ' + url);
      break;
    default:
      exec('xdg-open', [url]);
  }
}

app.prepare().then(() => {
  createServer((req, res) => {
    // 访问
    handle(req, res, parse(req.url, true))
  }).listen(port, (err) => {
    if(err) throw err;
    console.log(colorsjs.green("开启 url: http://localhost:" + port));
    // exec('open /Users/tuliuxiang/Desktop/GITFilter/nest-learn/dist/src')
    exec('cd ~ && cd /Users/tuliuxiang/Desktop/GITFilter/nest-learn/dist/src && node main.js', {}, (err, stdout, stderr) => {
      console.log(colorsjs.red('Error -->  '), err);
      console.log('stdout:', stdout);
      console.log('stderr:', stderr);
      // 端口关闭后执行 callback 函数
      // setTimeout(() => {
      //   openDefaultBrowser("http://localhost:3535")
      //   openDefaultBrowser("http://localhost:" + port + "/jy")
      // }, 1000*10)
    })
    setTimeout(() => {
      openDefaultBrowser("http://localhost:3535")
      openDefaultBrowser("http://localhost:" + port + "/jy")
    }, 1000*60)
  })
})

